package org.tao.lightningmq.broker.utils;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author lht
 * @date 2025/1/3 - 16:26
 * @description: 自旋锁
 */
public class SpinLock implements PutMessageLock, AckMessageLock {

    private final AtomicInteger state;

    public SpinLock() {
        state = new AtomicInteger(0);
    }

    @Override
    public void lock() {
        do {
            int result = state.getAndIncrement();
            if (result == 1) {
                return;
            }
        } while (true);
    }

    @Override
    public void unlock() {
        if (state.get() == 0) {
            return;
        }
        state.decrementAndGet();
    }
}
